package main

import (
	"flag"
	"os"
	"os/signal"
	"pipeline/config"
	"pipeline/log"
	"pipeline/middleware_mgr"
	"syscall"
	"testing"

	_ "github.com/go-sql-driver/mysql"
	"github.com/sirupsen/logrus"
)

var (
	confFile string //配置文件路径
)

func init() {
	initArgs()
}

// 解析命令行参数
func initArgs() {
	flag.StringVar(&confFile, "conf", "config/pipeline.toml", "pipeline -conf path/to/pipeline.toml")
	testing.Init()
	flag.Parse()
}

func signalExit() chan int {
	exitChan := make(chan int)
	signalChan := make(chan os.Signal, 1)
	go func() {
		select {
		case sig := <-signalChan:
			middleware_mgr.Stop()
			logrus.Info("got exit signal:", sig)
			os.Exit(1)
		}
	}()
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
	return exitChan
}

func main() {
	var (
		err  error
		conf = config.InitConf(confFile)
	)
	//初始化日志配置
	if err = log.InitLog(conf.LogConfig); err != nil {
		logrus.Error(err.Error(), "init logrus fail")
		return
	}

	// 初始化Python脚本目录
	if err = os.MkdirAll(conf.PythonScriptDir, 0755); err != nil {
		logrus.Error(err.Error(), "init python dir fail")
		return
	}

	// 初始化ETCD连接
	if err = middleware_mgr.InitMiddleware(conf); err != nil {
		logrus.Fatal("初始化失败:", err)
		return
	}
	logrus.Info("init middleware succ.")

	// 启动后台服务
	go middleware_mgr.HealthKeeper() //节点情况
	logrus.Info("start HealthKeeper succ.")
	go middleware_mgr.ConfigWatcher() //配置更新
	logrus.Info("start ConfigWatcher succ.")

	logrus.Println("服务启动成功")
	<-signalExit()
	logrus.Println("服务关闭")
}
